package biznussoft.metercor.fragments;

import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import biznussoft.metercor.MainActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.adapter.ServiceOrderAdapter;
import biznussoft.metercor.adapter.ServiceOrderAdapter.ViewHolder;
import biznussoft.metercor.entity.AccountModel;
import biznussoft.metercor.entity.ActivityModel;
import biznussoft.metercor.entity.ItemModel;
import biznussoft.metercor.entity.MapModel;
import biznussoft.metercor.entity.ServiceOrderModel;
import biznussoft.metercor.listener.Globallistener;
import biznussoft.metercor.utils.CustomProgressDialog;
import biznussoft.metercor.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class ServiceOrderRecordsFragment  extends Fragment implements OnItemClickListener{
	private RestClient client;
	private Dialog progressDialog;
	public static ArrayList<MapModel> mapList;
	public static ArrayList<ItemModel> modelList;
	private ListView lv;
	static ArrayList<ServiceOrderModel> serviceOrderList;
	public static ArrayList<ItemModel> manufacturerList;
	static HashMap<String, ArrayList<ActivityModel>> activityDetailsList;
	Globallistener listener;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.service_order_records, null);
	}      
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		MenuItem mytrack = menu.add("MyTrack");
		MenuItemCompat.setShowAsAction(mytrack, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		mytrack.setIcon(R.drawable.track); 

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		
		if(item.getTitle().equals("MyTrack")){
			listener.getSignature("track");}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		
		listener = (Globallistener) getActivity();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.listview);
		client =  MainActivity.mActivity.client;
		AccountModel.api_Version = getString(R.string.api_version);
		progressDialog = CustomProgressDialog.getInstance().createProgressDialog(getActivity());
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.show();
		retriveLeads();
		
		lv.setOnItemClickListener(this);

	}
                      
	

	
	/*
	 * change to startdate and end date
	 */
	public void retriveLeads()        
	{
		try{        
			
			String serviceOrder = "SELECT Name,Id,FConnect__Account__c,FConnect__Account_Name__c,FConnect__Bill_To_Address__c,FConnect__Contact_Name__c,FConnect__Phone__c,FConnect__Priority__c, FConnect__Contact_Email__c, Site_Status__c ,FConnect__Status__c,Service_Name__c, Estimated_Start_Date__c,Estimated_End_Date__c, FConnect__Technician_used__c FROM FConnect__Service_Order__c where FConnect__Technician_used__c="+"'"+Session.sTechnicianId+"'";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), serviceOrder);
			Log.i("NCS", "Response is  :"+restRequest);
			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {
						
						progressDialog.dismiss();
						Log.i("NCS", "Response is  :"+result);
						JSONObject jsonObject1 = new JSONObject(result         
								.toString());

						JSONArray jsonArray = jsonObject1
								.getJSONArray("records");

						mapList = new ArrayList<MapModel>();
						serviceOrderList = new ArrayList<ServiceOrderModel>();
						activityDetailsList = new HashMap<String, ArrayList<ActivityModel>>();
						
						Gson _gson = new Gson();
						for (int i = 0; i < jsonArray.length(); i++) {

							if (!jsonArray.isNull(i)) {

								ServiceOrderModel bean = _gson.fromJson(jsonArray.getString(i),ServiceOrderModel.class);
								String ID = jsonArray.getJSONObject(i).getString("Id");
								String billingAddress = jsonArray.getJSONObject(i).getString("FConnect__Bill_To_Address__c");

								if(billingAddress.length()>10){
									if(billingAddress.contains(" ")){
										String address = billingAddress.replace(" ", "%20");
										new MapTask().execute(address,billingAddress,jsonArray.getJSONObject(i).getString("Name"),jsonArray.getJSONObject(i).getString("FConnect__Account_Name__c"));                
									}               
								}
								
								
								
								serviceOrderList.add(bean);                

							}

						}

						showRecords();
              
					} catch (Exception e) {
						
						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}
		
		/*try{

			String accounts = "select id,name from Model__c";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {         
						Log.i("NCS", "Response is  :"+result);
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						modelList = new ArrayList<ItemModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ItemModel bean = _gson.fromJson(jsonArray.getString(i), ItemModel.class);
								modelList.add(bean);
							}

						}


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {}
			});




		}catch(Exception ex){

		}*/
		try{

			String accounts = "select id,name from Manufacturer__c";
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {    

						Log.i("NCS", "Response is  :"+result);
						JSONObject jsonObject1 = new JSONObject(result.asString());
						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						manufacturerList = new ArrayList<ItemModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ItemModel bean = _gson.fromJson(jsonArray.getString(i), ItemModel.class);
								manufacturerList.add(bean);
							}

						}


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {}
			});




		}catch(Exception ex){

		}


	}
	class ListComparator implements Comparator<ServiceOrderModel>,Serializable
	{
	public int compare(ServiceOrderModel o1, ServiceOrderModel o2)
	{

	return o1.getName().compareTo(o2.getName());

	}

	}

	public void showRecords(){
		
		Collections.sort(serviceOrderList, new ListComparator());
		ServiceOrderAdapter adapter = new ServiceOrderAdapter(getActivity(),serviceOrderList);
		lv.setAdapter(adapter);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// TODO Auto-generated method stub
		ServiceOrderModel model = serviceOrderList.get(position);
		Session.sAccountId = model.getAccount();     
		setHasOptionsMenu(false);                
		listener.getResponse(position);
	}
	
	class ServiceOrderAdapter extends BaseAdapter {
		boolean checkArray[]; 	
		ArrayList<ServiceOrderModel> listdata;
		Context mContext;
		public ServiceOrderAdapter(Context context, ArrayList<ServiceOrderModel> list) {
			this.listdata = list;
			this.mContext = context;
			checkArray = new boolean[list.size()];
		}

		public int getCount() {
			return listdata.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}
		
		public class ViewHolder{             
			public TextView name;                 
			public TextView phno;                
			public TextView Email;            
			public TextView title;             
			public ImageView image;
			public RelativeLayout rLayout;
		}

		public View getView(final int position, View v, ViewGroup parent) {
			ViewHolder holder;
			if(v == null){
				holder = new ViewHolder();
				LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflator.inflate(R.layout.common_details_page, null);
				holder.name  = (TextView) v.findViewById(R.id.text1);
				holder.title  = (TextView) v.findViewById(R.id.text2);
				holder.Email = (TextView) v.findViewById(R.id.text3);
				holder.image = (ImageView) v.findViewById(R.id.imageview);
				holder.rLayout  = (RelativeLayout) v.findViewById(R.id.rrlayout_1);
				v.setTag(holder);
			}else{
				holder = (ViewHolder) v.getTag();
				holder.image.setImageResource(R.drawable.serviceorder_button_icon);
			}

			 v.setTag(holder);
		      holder.rLayout.setId(position);
		      
			final ServiceOrderModel bean = listdata.get(position);
				holder.name.setText(bean.getName());
				holder.title.setText(bean.getAccountName());
				holder.Email.setText(bean.getContact());
				
				
				holder.rLayout.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						Session.sSerOrderId = bean.getId();
						Session.sAccountId = bean.getAccount();
						setHasOptionsMenu(false);                
						listener.getResponse(position);
						
						for (int i = 0; i <listdata.size(); i++) {
		                    if (v.getId() == i) {
		                    	checkArray[i] = true;
		                    } else {
		                    	checkArray[i] = false;
		                    }
		                }
		                notifyDataSetChanged();
		            }
					
				});           
				
				if (checkArray[position]) {
		            holder.image.setImageResource(R.drawable.serviceorder_button_icon_active);
		        } else {
		            holder.image.setImageResource(R.drawable.serviceorder_button_icon);
		        }
				Log.i("NCS","Records  :"+bean.getInstallesProduct()+" : "+bean.getProductId2()+" : "+bean.getAgreementName()+" : "+bean.getEntitleGroupName()+" : "+bean.getServiceName()+" : "+bean.getServiceDescription());
			
			return v;
		}
	}  

	class MapTask extends AsyncTask<String, Void, Void>{                 

		@Override
		protected Void doInBackground(String... params) {
			getLocationInfo(params[0],params[1],params[2],params[3]);
			return null;
		}                 



	}
	
	

	public  void getLocationInfo(String address,String addess2,String serviceOrder,String accountname) {

		try{
			//		http://maps.google.com/maps/api/geocode/json?address=10 Main Rd., New York, NY, USA, 31349&sensor=false
			HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?address="+address+"&sensor=false");
			HttpClient client = new DefaultHttpClient();
			HttpResponse response;
			StringBuilder stringBuilder = new StringBuilder();

			try {
				response = client.execute(httpGet);                                                  
				HttpEntity entity = response.getEntity();
				InputStream stream = entity.getContent();
				int b;
				while ((b = stream.read()) != -1) {
					stringBuilder.append((char) b);
				}
			}  catch (Exception e) {

				Log.i("TPT", "Exception 1 is  :  " + e.getMessage());
			}

			JSONObject jsonObject = new JSONObject();
			try {
				jsonObject = new JSONObject(stringBuilder.toString());
				getGeoPoint(jsonObject ,addess2,serviceOrder,accountname);
			} catch (Exception e) {
				Log.i("TPT", "Exception 2 is  :  " + e.getMessage());
			}
		}catch(Exception ex){
			Log.i("TPT", "Main Exception  is  :  " + ex.getMessage());
		}


	}

	public  void getGeoPoint(JSONObject jsonObject,String address,String serviceOrder,String accountname) {

		Double lon = new Double(0);
		Double lat = new Double(0);

		try {

			MapModel model = new MapModel();


			lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
					.getJSONObject("geometry").getJSONObject("location")
					.getDouble("lng");

			lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
					.getJSONObject("geometry").getJSONObject("location")
					.getDouble("lat");


			model.setLatitude(lat);
			model.setLongitude(lon);
			model.setAddress(address);
			model.setServiceOrder(serviceOrder);
			model.setAccountName(accountname);

			mapList.add(model);



		} catch (Exception e) {
			Log.i("NCS", "Exception  3 is  :  " + e.getMessage());
		}


	}


	
}
